from lxml import etree
from requests.auth import HTTPProxyAuth
from tool import *
from sql import sqlseverDB
import requests,concurrent.futures

ms = sqlseverDB('{SQL Server}',SQL_SERVER, 'SuMaiTongPol', SQL_USER, SQL_PWD)

def getCKDL(force=0):
    
    if force==0 or not os.path.exists(HK_PROXY_PATH):
        datas=[]
        rs=ms.ExecQuery('select ip,httpport,socks5port,uid,upwd from hkproxy where state=1 and ip!=?',('localhost',))
        print(f'共有:{len(rs)} 个香港代理,开始制造cookie')
        
        #先获取无代理CK
        ck0= asyncio.run(get_amazon_ck())
        datas.append([ck0,None])
        aff0=ms.ExecNoQuery('update hkproxy set cookie=? where [ip]=?',(ck0,'localhost'))
        print(f'保存本地ck到数据库状态:{aff0}')

        for ipstr,httport,sockport,uid,upwd in rs:
            while True:
                rescj=create_browser_environment(f'亚马逊_{ipstr}',[ipstr,sockport,uid,upwd])
                print(rescj)
                if rescj['code']==0 and rescj['msg']=='Success':
                    bid=rescj['data']['id']
                    bnum=rescj['data']['serial_number']
                    print(f'成功创建环境:亚马逊_{ipstr},bip:{bid},序列号:{bnum}')
                    break
                
                time.sleep(1)
        
            ck=asyncio.run(get_amazon_ck(bid))
            if ck=='代理错误':
                resdel=del_browser_environment(bid)
                if resdel['code']==0:
                    print(f'代理错误跳过,成功删除环境:{bid}')
                
                continue
                
            aff0=ms.ExecNoQuery('update hkproxy set cookie=? where [ip]=?',(ck,ipstr))
            print(f'保存{ipstr}的ck到数据库状态:{aff0}')

            datas.append([ck,[ipstr,httport,uid,upwd]])

            resdel=del_browser_environment(bid)
            if resdel['code']==0:
                print(f'成功删除环境:{bid}')
        
        with open(HK_PROXY_PATH,'w',encoding='utf-8') as f:

            json.dump(datas,f,ensure_ascii=False)
        
        print(f'已保存ck文件置:{HK_PROXY_PATH}')
        

    else:
        with open(HK_PROXY_PATH,'r',encoding='utf-8') as f:
            datas=json.load(f)

    return datas

def main():
    getCKDL()
    os.system('python CJSeller.py')

if __name__=='__main__':

    main()